﻿

using System;
using System.Collections.Generic;
using System.Linq;
using NetCore.ORM;
using NetCore.Model;
namespace NetCore.BLL
{
    public class NotifyService : SerivceBase, INotifyService
    {

        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<NotifyEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(NotifyEntity.__IsDeleted, false);
            return this.Query<NotifyEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public NotifyEntity GetById(string id)
        {
            return this.GetById<NotifyEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(NotifyEntity entity, ref string strError)
        {
          
            if (string.IsNullOrWhiteSpace(entity.NotifyId))
            {
                entity.NotifyId = MyGenerateHelper.GenerateOrder();
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<NotifyEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="ligerGrid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                               NotifyEntity._PrimaryKeyName ,
                                NotifyEntity.__SenderUserId,
                                NotifyEntity.__Title,
                                NotifyEntity.__ReceiveUserId,
                                NotifyEntity.__FormId
                           }, ligerGrid.keyWord)
                           );
            }
            ligerGrid= this.Query<NotifyEntity>(ligerGrid, criter);
            if (ligerGrid != null && ligerGrid.Rows != null)
            {
                List<NotifyEntity> notifyEntities = (List<NotifyEntity>)ligerGrid.Rows;
                if (notifyEntities != null && notifyEntities.Count > 0)
                {
                    notifyEntities.ForEach(x=>{
                        var sendUser = this.GetById<UserEntity>(x.SenderUserId);
                        if (sendUser != null)
                        {
                            x.SenderName = sendUser.RealName;
                        }
                        
                    });
                }
            }
            return ligerGrid;

        }
        #endregion

        #region 扩展方法

        public LigerGrid MyNotify(LigerGrid ligerGrid,string userid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,
                           Expression.Like(new string[] {
                                NotifyEntity._PrimaryKeyName ,
                                NotifyEntity.__SenderUserId,
                                NotifyEntity.__Title,
                                NotifyEntity.__ReceiveUserId,
                                NotifyEntity.__FormId
                           }, ligerGrid.keyWord)
                           );
            }
            if (string.IsNullOrWhiteSpace(ligerGrid.sortOrder))
            {
                ligerGrid.sortOrder = "desc";
            }
            if (string.IsNullOrWhiteSpace(ligerGrid.sortName))
            {
                ligerGrid.sortName = EntityBase.__LastModifyDate;
            }
            var status = ligerGrid.GetValue("Status");
            if (!string.IsNullOrWhiteSpace(status))
            {
                criter= Expression.And(criter, Expression.Eq(NotifyEntity.__Status, status));
            }
            criter = Expression.And(criter,Expression.Eq(NotifyEntity.__ReceiveUserId, userid));
            ligerGrid= this.Query<NotifyEntity>(ligerGrid, criter);
            if (ligerGrid != null && ligerGrid.Rows != null)
            {
                List<NotifyEntity> notifyEntities = (List<NotifyEntity>)ligerGrid.Rows;
                if (notifyEntities != null && notifyEntities.Count > 0)
                {
                    notifyEntities.ForEach(x => {
                        var sendUser = this.GetById<UserEntity>(x.SenderUserId);
                        if (sendUser != null)
                        {
                            x.SenderName = sendUser.RealName;
                        }

                    });
                }
            }
            return ligerGrid;

        }

        public bool ReaderNotify(string notifyid,ref string strError)
        {
            if (string.IsNullOrWhiteSpace(notifyid))
            {
                strError = "参数异常";
                return false;
            }
            var notify = this.GetById<NotifyEntity>(notifyid);
            if (notify == null)
            {
                strError = "当前消息不存在，参数错误";
                return false;
            }
            if (!notify.ReceiveUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
            {
                return true;
            }
            if (notify.Status >= 1)
            {
                return true;
            }
            notify.Status = 1;
            notify.ExpireTime = DateTime.Now;
          //  notify.ex
            return this.SaveOrUpdate<NotifyEntity>(notify);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="users">接收人多人可用逗号隔开</param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool Send(string senderUser,string users,string title, string content, ref string strError)
        {
            return Send(senderUser,users, "", NotifyTypeEnum.Default, title, content, ref strError);
        }
        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="users">接收人多人可用逗号隔开</param>
        /// <param name="formid"></param>
        /// <param name="formType"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool Send(string senderUser, string users, string formid,
            NotifyTypeEnum formType, string title, string content, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(users))
            {
                strError = "接收用户不存在";
                return false;
            }
            NotifyEntity entity = null;
            if (!string.IsNullOrEmpty(formid) && formType != NotifyTypeEnum.Default)
            {
                ICriterion criter = Expression.And(Expression.Eq(NotifyEntity.__FormType, formType.GetHashCode()),
                    Expression.And(Expression.Eq(NotifyEntity.__FormId, formid),
                    Expression.Eq(NotifyEntity.__IsDeleted, false)));
                entity = this.Query<NotifyEntity>(criter).FirstOrDefault();

            }
            if (entity != null)
            {
                strError = "请不要重复发送消息";
                return false;
            }
          
            var arrReceive = users.Split(new char[] { ';', ',' });
            List<NotifyEntity> notifies = new List<NotifyEntity>();
            foreach (var user in arrReceive)
            {
                if (!string.IsNullOrWhiteSpace(user))
                {
                    var userTry= this.GetById<UserEntity>(user);
                    if (userTry == null)
                    {
                        strError = "用户不存在";
                        return false;
                    }
                    notifies.Add(new NotifyEntity
                    {
                        Content = content,
                        CreateBy = ApplicationEnvironments.DefaultSession.UserId,
                        CreateDate = DateTime.Now,
                        LastModifyDate = DateTime.Now,
                        LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId,
                        SenderUserId = senderUser,
                        ReceiveUserId = user,
                        SendDate = DateTime.Now,
                        NotifyId = MyGenerateHelper.GenerateOrder(),
                        FormId = formid,
                        Title=title,
                        FormType = formType.GetHashCode(),
                    });
                }
            }
            if (notifies != null && notifies.Count > 0)
            {
                using (var tran = this.Begin())
                {
                    try
                    {
                        this.BatchInsert<NotifyEntity>(notifies, ref strError);
                        this.Commit();
                    }
                    catch (Exception ex)
                    {
                        this.Rollback();
                        strError = ex.Message;
                        return false;
                    }
                }
            }
            return true;
          
        }
        #endregion

    }
}